<template>
	<div class="content-page">
		<div class="content-nav">
			<el-breadcrumb class="breadcrumb" separator="/">
				<el-breadcrumb-item :to="{ name: 'dashboard' }">首页</el-breadcrumb-item>
				<el-breadcrumb-item>活动管理</el-breadcrumb-item>
				<el-breadcrumb-item>活动人员</el-breadcrumb-item>
			</el-breadcrumb>
			<div class="operation-nav">
				<el-button type="primary" @click="goBackPage" icon="arrow-left">返回列表</el-button>
			</div>
		</div>
		<div class="content-main">
			<div class="form-table-box">
				<el-form ref="infoForm" :rules="infoRules" :model="infoForm" label-width="120px">
					<el-form-item label="活动名称" prop="activityName">
						<el-input v-model="infoForm.activityName"></el-input>
					</el-form-item>
					<el-form-item label="活动时间" prop="time">
						<el-date-picker v-model="infoForm.time" type="datetimerange" placeholder="选择时间范围" format="yyyy-MM-dd">
						</el-date-picker>
					</el-form-item>
					<el-form-item label="活动封面" prop="activityImage">
						<div class="flex align-items">
							<div v-if="infoForm.activityImage" class="pos-r">
								<el-image :src="infoForm.activityImage" class="image-show" style="width: 165px;height: 105px;" />
								<i class="el-icon-error pos-a delBtn" @click="delBtnFun"></i>
							</div>
							<el-upload class="image-uploader" name="upfile" :action="imgServer" :on-success="handleUploadImageSuccess"
							 :limit="1" :on-progress="uploadingImgAction" :on-remove="handleRemove" :before-upload="beforeUpload" v-else>
								<i class="el-icon-plus image-uploader-icon"></i>
								<div slot="tip" class="el-upload__tip">{{uploadingImgStatus?'压缩中...请稍等':'图片尺寸:678*380 大小限制:2M以内'}}</div>
							</el-upload>

						</div>
					</el-form-item>
					<el-form-item label="活动介绍" prop="simple_desc">
						<div class="ueditor-wrap">
							<vue-ueditor-wrap v-model="msg" :config="ueditorConfig.config" @ready="ueditorConfig.ready"></vue-ueditor-wrap>
						</div>
						<div class="form-tip"></div>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="onSubmitInfo">确定保存</el-button>
						<el-button @click="goBackPage">取消</el-button>
					</el-form-item>
				</el-form>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		getCategoryList,
		addVideo,
		setActivity,
		getVideoToken,
		setVideoPfop,
		getVideoPfopStatus,
		getActivityDetail
	} from '@/api/permission'
	import ueditorConfig from '@/config/ueditorConfig'
	import config from '@/config/baseUrl'
	import uploadFun from '@/assets/js/qiniu'
	import videoConfig from '@/assets/js/videoConfig'
	export default {
		data() {
			return {
				categoryList: [],
				ueditorConfig: ueditorConfig,
				imgServer: `${config.baseUrl}/vms/v1/image/upload`,
				videoServer: `${config.baseUrl}/vms/v1/video/upload`,
				uploadingImgStatus: false,
				srcList: [],
				msg: '', //富文本
				infoForm: {
					id: '',
					activityName:'',
					activityImage:'',
					time:[],
					startDate:'',
					endDate:'',
					activityDesc:''
				},
				infoRules: {
					activityName: [{
						required: true,
						message: '请输入名称',
						trigger: 'blur'
					}],
					activityImage: [{
						required: true,
						message: '请上传封面',
						trigger: 'change'
					}],
					time:[{
						required: true,
						message: '请选择时间',
						trigger: 'change'
					}]
				},
				videoPercentage: 0,
				uploading_video: false, //新增部分
				change_video_status: false,
				video_Config: videoConfig,
				show_video: true,
				timer: null,
				dialogVisible: false
			}
		},
		methods: {
			uploadingImgAction(event, file, fileList) {
				let percentage = parseInt(event.loaded / event.total * 100)
				if (percentage == 100) {
					this.uploadingImgStatus = true
				}
			},
			handleRemove() {
				this.infoForm.activityImage = ''
			},
			goBackPage() {
				this.$router.push({
					name: 'game'
				})
			},
			delBtnFun() {
				this.infoForm.activityImage = ''
			},
			beforeUpload(file) {
				let self = this
				if ((file.size / (1024 * 1024)) > 2) {
					self.$notify({
						title: '提示',
						message: '文件太大2M以内'
					})
					return false
				}
			},
			p(s) {
			     return s < 10 ? '0' + s : s
			},
			parserDate(d){
				return d.getFullYear() + '-' + this.p((d.getMonth() + 1)) + '-' + this.p(d.getDate())
			},
			onSubmitInfo() {
				let self = this
				self.$refs['infoForm'].validate((valid) => {
					if (valid) {
						self.infoForm.activityDesc = self.msg
						if(self.infoForm.time.length){
							self.infoForm.startDate =self.parserDate(new Date(self.infoForm.time[0]))
							self.infoForm.endDate =self.parserDate(new Date(self.infoForm.time[1]))
						}
						setActivity(self.infoForm).then((res) => {
							self.$message({
								message: '活动保存成功',
								type: 'success'
							});
							if (self.infoForm.id) {
								self.$router.push({
									name: 'game'
								})
							}
						}).catch(err => {
							console.log(err)
						})
					} else {
						return false;
					}
				});
			},
			handleUploadImageSuccess(res, file) {
				this.uploadingImgStatus = false
				if (res.respCode.code == "EDI-10000") {
					this.infoForm.activityImage = res.data.fileUrl
					this.srcList = [res.data.fileUrl]
				}
			},
			getInfo(id) {
				//加载商品详情
				let self = this
				getActivityDetail({
					id: id
				}).then((res) => {
					for (let key in self.infoForm) {
						if (key == 'activityDesc') {
							self.msg = res[key]
						}
						self.video_Config[`sources`][0].src = res.videoUrl
						self.infoForm[key] = res[key]
						self.infoForm.time = [res.startDate,res.endDate]
					}
				})
			},
			getCategoryListFun() {
				let self = this
				getCategoryList({
					index: 0,
					size: 99
				}).then(res => {
					self.categoryList = res.content
				})
			},
			//文件
			handleClick() {
				this.$refs.input.value = ''
				this.$refs.input.click();
			},
			handleChange(ev) {
				const files = ev.target.files;
				if (!files) return;
				this.uploadFiles(files);
			},
			uploadFiles(files) {
				let self = this
				let observer = {
					next(res) {
						self.videoPercentage = parseInt(res.total.percent)
					},
					error(err) {
						// ...
					},
					complete(res) {
						console.log("完成==》", res)
						if (res.key) {
							setVideoPfop({
								key: res.key
							}).then(res => {
								console.log(res)
								self.change_video_status = true
								self.timer = setInterval(() => {
									getVideoPfopStatus({
										id: res.persistentId
									}).then(res => {
										if (res[0].status.code == 0) {
											clearInterval(self.timer)
											self.dialogVisible = false
											self.change_video_status = false
											self.video_Config[`sources`][0].src = res[0].url
											self.infoForm.videoUrl = res[0].url
										}
									})
								}, 1000)
							})
						}
					}
				}
				self.dialogVisible = true
				self.subscription = uploadFun(self.$store.state.videoToken, files[0], observer)
			},
			close() {
				let self = this
				self.change_video_show = false
				self.dialogVisible = false
				self.change_video_status = false
				if (self.subscription) {
					self.subscription.unsubscribe()
				}
				clearInterval(self.timer);
			},
			beforeDestroy() {
				clearInterval(self.timer);
			},
			handleKeydown(e) {
				if (e.target !== e.currentTarget) return;
				if (e.keyCode === 13 || e.keyCode === 32) {
					this.handleClick();
				}
			}
		},
		components: {},
		mounted() {
			let self = this
			if (self.$route.query.id) {
				self.getInfo(self.$route.query.id)
			}
			clearInterval(self.timer);
			if (!self.$store.state.videoToken) {
				getVideoToken().then(res => {
					self.$store.commit('SET_VIDEOTOKEN', res.token)
				})
			}
			this.getCategoryListFun()
		}
	}
</script>

<style>
	.image-uploader {
		min-height: 105px;
		height: auto !important;
	}

	.image-uploader .el-upload {
		border: 1px solid #d9d9d9;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.image-uploader .el-upload:hover {
		border-color: #20a0ff;
	}

	.image-uploader .image-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 187px;
		height: 105px;
		line-height: 105px;
		text-align: center;
	}

	.image-show {
		width: 187px;
		height: 105px;
		display: block;
	}

	.image-uploader.new-image-uploader {
		font-size: 28px;
		color: #8c939d;
		width: 165px;
		height: 105px;
		line-height: 105px;
		text-align: center;
	}

	.image-uploader.new-image-uploader .image-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 165px;
		height: 105px;
		line-height: 105px;
		text-align: center;
	}

	.delBtn {
		position: absolute;
		font-size: 24px;
		right: -12px;
		top: -12px;
		color: #FF5D6A;
		cursor: pointer;
		z-index: 999;
	}
</style>
